package cn.geminis.fabric.service.configuration;

import cn.geminis.core.util.FileUtils;
import org.hyperledger.fabric.gateway.Gateway;
import org.hyperledger.fabric.gateway.Identities;
import org.hyperledger.fabric.gateway.Wallets;
import org.hyperledger.fabric.sdk.Enrollment;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author puddi
 */
@Configuration
public class GatewayConfiguration {

    @Value("${geminis.fabric.networkConfigPath}")
    private String networkConfigPath;
    @Value("${geminis.fabric.mspId}")
    private String mspId;
    @Value("${geminis.fabric.certPem}")
    private String cert;
    @Value("${geminis.fabric.privateKeyPem}")
    private String privateKey;

    @Bean
    public Gateway getGateway() {
        try {
            var certValue = new String(FileUtils.readFile(this.cert));
            var privateKeyValue = new String(FileUtils.readFile(this.privateKey));

            //根据connection.json 获取Fabric网络连接对象
            var builder = Gateway.createBuilder()
                    .identity(Identities.newX509Identity(
                            this.mspId,
                            Identities.readX509Certificate(certValue),
                            Identities.readPrivateKey(privateKeyValue)
                    ))
                    .networkConfig(Paths.get(this.networkConfigPath));
            //连接网关
            return builder.connect();
        } catch (Exception e) {
            throw new RuntimeException("初始化Fabric Gateway错误", e);
        }
    }

}
